package auctionhaus

import java.util.Date;
import java.text.DecimalFormat
import java.text.NumberFormat;

class Bid {

	private static final Float BID_INC = 0.5f;

	Float amount;
	Date dateCreated;

	static belongsTo = [bidder:Customer, listing:Listing]

	/**
	 * UI-1: The listing detail page will asynchronously load and display a list of the last 10 bids placed on the item showing the user, date/time, and amount. 
	 * The implementation of the lookup of these results must be done with a Named Query. (Integration Test)
	 */
	static namedQueries ={
		listingRecentBids { thisId ->
			eq 'listing.id',thisId
			maxResults(10)
			order('dateCreated','desc')
		}
	}

	static constraints = {
		amount(scale: 2, min: 0F, nullable: false, validator : {val, obj ->
			if( val < obj.listing.startingPrice ){
				return false
			}
			else if(obj.listing.bids == null ){
				return true
			}

			int size = obj.listing.bids.size()

			if (size < 2){
				return true
			}
			else {
				if(Double.compare(val,obj.listing.currentMinimumBid)>=0){
					return true;
				}
				else{
					return false;
				}
				
			}
	
		})	
	}

	public static String amountFormatter(def amount){
		if(amount != null) {
			NumberFormat fmt = NumberFormat.getCurrencyInstance()
			return fmt.format(amount)
		}
		else
			return amount
	}

	public String toString(){
		return amountFormatter(amount);
	}

}
